package com.example.musicservice;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Parcel;
import android.os.RemoteException;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.io.FileDescriptor;
import java.io.IOException;

public class MusicService extends Service {

    private MediaPlayer mMediaPlayer = null;

    public MusicService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mMediaPlayer = new MediaPlayer();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        try{//销毁mMediaPlayer
            if(mMediaPlayer != null){
                mMediaPlayer.reset();
                mMediaPlayer.release();
                mMediaPlayer = null;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return super.onUnbind(intent);
    }

    public class MyBinder extends Binder {

        public boolean isPlaying() {
            return mMediaPlayer.isPlaying();
        }

        public void play(String path) {
            try {
                mMediaPlayer.reset();//没有这个再播放会闪退
                mMediaPlayer.setDataSource(path);
                mMediaPlayer.prepare();
                mMediaPlayer.start();
                //Log.d("musicservice", "play");
            } catch (IOException e) {
                //Log.d("musicservice", "playerror");
                e.printStackTrace();
            }
        }

        public void pause() {
            mMediaPlayer.pause();
        }

        public void resume() {
            mMediaPlayer.start();
        }

        //返回歌曲的长度，单位为毫秒
        public int getDuration(){
            return mMediaPlayer.getDuration();
        }

        //返回歌曲目前的进度，单位为毫秒
        public int getCurrenPostion(){
            return mMediaPlayer.getCurrentPosition();
        }

        //设置歌曲播放的进度，单位为毫秒
        public void seekTo(int mesc){
            mMediaPlayer.seekTo(mesc);
        }
    }
}